﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using System.Data.Objects.SqlClient;
using System.Data.Objects;

namespace DotaHelp.Controllers
{
	public class NewsController : Controller
	{
		DotaModel model = new DotaModel();

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			model.Dispose();
			
		}
			

		public ActionResult List(DateTime? on = null, string type = null, bool isPartial = false)
		{            
			ViewBag.isPartial = isPartial;
		
			var onDate = on.HasValue?on.Value.Date.AddDays(1).AddSeconds(-1):DateTime.UtcNow.NowByAstana();
			var onDate2 = onDate.AddDays(-1);

			ViewBag.onDate = onDate;

			Dictionary<string, IQueryable<IPublishItem>> items = new Dictionary<string, IQueryable<IPublishItem>>()
			{
				{ "Новости",  model.Topics.Where(i=>!i.IsDeleted && i.IsNews).Where(i => i.Date > onDate2 && i.Date <= onDate)},
				{ "Форум",  model.Topics.Where(i=>!i.IsDeleted && !i.IsNews).Where(i => i.Date > onDate2 && i.Date <= onDate)},				
				{ "Гайды", model.Guides.Include("Hero").Where(i=>!i.IsDeleted).Where(i => i.Date >= onDate2 && i.Date <= onDate)},
				{ "Закупы", model.Purchases.Include("PurchasesItems").Include("Hero").Include("PurchasesItems.Item").Where(i=>!i.IsDeleted).Where(i => i.Date > onDate2 && i.Date <= onDate)},
				{ "Прокачки", model.Upgrades.Include("UpgradesItems").Include("Hero").Include("UpgradesItems.Skill").Where(i=>!i.IsDeleted).Where(i => i.Date > onDate2 && i.Date <= onDate)},
				{ "Команды", model.Commands.Include("CommandsHeroes").Include("CommandsHeroes.Hero").Where(i=>!i.IsDeleted).Where(i => i.Date > onDate2 && i.Date <= onDate)}
			};

			if (type != null && !items.ContainsKey(type)) type = null;
			
			ViewBag.type = type;

			ViewBag.ItemsKeys = items.Keys;

			IEnumerable<IPublishItem> list = null;
			if (type == null)
			{
				foreach (var item in items)
				{
					if (list == null)
					{
						list = item.Value.ToArray();
					}
					else
					{
						list = list.Union(item.Value.ToArray());
					}
				}
			}
			else
			{
				list = items[type];
			}

			list = list.OrderByDescending(r => r.Date);

			

			return isPartial && Request.IsAjaxRequest() ? (ActionResult)PartialView("List", list) : View("List", list);
		}

		public ActionResult LastNews()
		{
			return PartialView(model.Topics
				.Where(t => !t.IsDeleted && t.IsNews && t.Author.StartsWith("_admin_"))
				.OrderByDescending(t => t.Date)
				.FirstOrDefault());
		}
	}
}
